﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PB.Airsoft.Business.Shop;
using PB.Airsoft.Business.Shop.Interfaces;
using PB.Airsoft.Business.Shop.Entities;
using PB.Airsoft.NHibernateWrapper;
using System.Configuration;
using PB.Airsoft.Core.Unity;
using NHibernate.Criterion;
using PB.Airsoft.Business.User;
using PB.Airsoft.Business.Item.Interfaces;

namespace PB.Airsoft.Provider.NHibernate.Shop
{
    public class NHibernateShopProvider : ShopProvider
    {
        private ISessionManager CreateSessionManager(bool readOnly)
        {
            return new SessionManager(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString, readOnly);
        }

        public override List<IShopLot> GetShopLots(ShopType shopType)
        {
            using (var sm = CreateSessionManager(true))
            {
                var criteria = sm.Session.CreateCriteria(IoC.GetRegisteredType<IShopLot>());
                criteria.Add(Expression.Eq("ShopType", (int)shopType));
                return criteria.List().Cast<IShopLot>().ToList();
            }
        }

        public override void Buy(Guid shopLotId, Guid buyerId)
        {
            using (var sm = CreateSessionManager(false))
            {
                var shopLot = (IShopLot)sm.Session.Get(IoC.GetRegisteredType<IShopLot>(), shopLotId);

                UserManager.IncrementMoney(buyerId, -shopLot.Price);

                if (shopLot.ShopType == ShopType.FleaMarket)
                    UserManager.IncrementMoney(shopLot.UserId, shopLot.Price);

                UserManager.AddItem(buyerId, shopLot.ItemId);

                sm.Session.Delete(shopLot);

                sm.Commit();
            }
        }

        public override void Sell(IItem itemToSell, decimal money, Guid sellerId)
        {
            using (var sm = CreateSessionManager(false))
            {
                var shopLot = IoC.GetInstance<IShopLot>();
                shopLot.Id = Guid.NewGuid();
                shopLot.ItemId = itemToSell.Id;
                shopLot.Price = money;
                shopLot.ShopType = ShopType.FleaMarket;
                shopLot.UserId = sellerId;

                sm.Session.Save(shopLot);

                UserManager.RemoveItem(sellerId, itemToSell.Id);

                sm.Commit();
            }
        }
    }
}
